<?php 

class JSON {
	var $data;
	var $content;
	var $filePath;

	function __construct($filePath){
		$this->filePath = $filePath;
		$this->content = file_get_contents($filePath);
		$this->init();
	}

	function init(){
		//处理掉多余的逗号
		$this->content = preg_replace("/,[\s\n\r\t]*([\}\]])/","$1",$this->content);
		$this->data = json_decode($this->content,true);

	}

	// function anasylze(){
	// 	$token = array(
	// 		'LB' => '{',
	// 		'RB' => '}',
	// 		'LM' => '[',
	// 		'RM' => ']',
	// 		'FUNCTION' => 'function',
	// 		'COMMA' => ',',
	// 		'WORD' => '[\w-]+',
	// 		'STRING' => "[\'\"]"
	// 	);

	// 	preg_match_all('/' . implode('|',$token) . '/',$this->content,$arr,PREG_OFFSET_CAPTURE);
	// 	print_r($arr);
	// }

	function output(){
		$out = json_encode($this->data);
		$count;
		$out = preg_replace_callback("/\{|\}|\,|\:|\[|\]/", function($matched) use (&$count,&$last){
			switch($matched[0]){
				case ':':
					return " : ";
				case '{':
					$last[] = $matched[0];
					$count++;
					return $matched[0] . "\n" . str_repeat("\t", $count);
				case '}':
					$count--;
					return "\n" . str_repeat("\t", $count) . $matched[0]; 
				case '[':
					$last[] = $matched[0];
					$count++;
					return $matched[0] . "\n" . str_repeat("\t", $count);
				case ']':
					$count--;
					return "\n" . str_repeat("\t", $count) . $matched[0]; 
				case ',':
					return $matched[0] . "\n" . str_repeat("\t", $count);
			}

		}, $out);
		return $out;
	}

	function save(){
		return file_put_contents($this->filePath,$this->output());
	}
}

// $a = new JSON('1.json');
// $a->save();

 ?>